package com.laterem.rtc.util;

import com.laterem.rtc.domain.UserDO;
import com.laterem.rtc.service.dto.UserDTO;
import jakarta.servlet.http.HttpServletRequest;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @creator: alan wu
 * @dateTime: 2023/5/20 00:24
 * @desc: 用户的持有者
 */
public class UserHolder {

    final static Map<String, UserDO> USER_CACHE = new ConcurrentHashMap<>();
    final static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    public static UserDO getUserDO(String token){
        UserDO userDO = USER_CACHE.get(token);
        if (!Objects.isNull(userDO)){
            Long expirationTime = 0l;
            long now = System.currentTimeMillis();
            // 用户登录过期，移除用户。
            if (now > expirationTime){
                USER_CACHE.remove(token);
                return null;
            } else {
                return userDO;
            }
        }
        return null;
    }

    public static UserDO getUserDO(HttpServletRequest request){
        String token = request.getHeader("laterem");
        return getUserDO(token);
    }

    public static void putUserDO(String token, UserDO userDO){
        USER_CACHE.put(token, userDO);
    }

    public static void setId(Integer id){
        threadLocal.set(id);
    }

    public static Integer getUid(){
        return threadLocal.get();
        // ToDo 临时
//        return "1";
    }
}
